# coding=utf8
import time
import threading
import subprocess

def callback_func():
    print('超时回调')


def time_out(interval, callback=None):
    def decorator(func):
        def wrapper(*args, **kwargs):
            t = threading.Thread(target=func, args=args, kwargs=kwargs)
            t.setDaemon(True)  # 设置主线程技术子线程立刻结束
            t.start()
            t.join(interval)  # 主线程阻塞等待interval秒
            if t.is_alive() and callback:
                return threading.Timer(0, callback).start()  # 立即执行回调函数
            else:
                return

        return wrapper

    return decorator


def command(cmd, timeout=60):
    """执行命令cmd，返回命令输出的内容。
    如果超时将会抛出TimeoutError异常。
    cmd - 要执行的命令
    timeout - 最长等待时间，单位：秒
    """
    p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
    t_beginning = time.time()
    while True:
        if p.poll() is not None:
            break
        seconds_passed = time.time() - t_beginning
        if timeout and seconds_passed > timeout:
            p.terminate()
            raise TimeoutError(cmd, timeout)
        time.sleep(1)
    return p.stdout.read()


@time_out(2, callback_func)
def task3(hh):
    print('**********task3****************')
    for i in range(3):
        time.sleep(1)
        print(i)
        print(hh)

@time_out(3, callback_func)
def task9():
    time.sleep(10)



@time_out(2, callback_func)
def task4(hh):
    print('**********task4****************')
    for i in range(3):
        # time.sleep(1)
        print(i)
        print(hh)


if __name__ == '__main__':
    #
    task9()